<?php
declare (strict_types = 1);
namespace app\controller;

use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\View;
use app\Common;

//Token管理类
class Sys{

    var $back = "<script>setTimeout(function(){history.back();},3000)</script>";
    
    public function index(){

    }


    //token验证
    public function app_info(){
        $all=Request::param();
        if(empty($all['token'])) return json(['code'=>0,'msg'=>'请登录!']);

        $token = new Token();
        $arr = $token->check_token($all['token']); 
        if($arr['code']<1){
            return json($arr);
        }
        $customer=$arr['customer'];

        $app_info = Db::table('app_config')->find(1);

        if(!$app_info) return json(['code'=>0,'msg'=>'Fail!']);

        $appid = $app_info['appid'];//'wx15d32cb44449c60f';
        $secret = $app_info['api_secret'];//"34d1ab0202953f1d537e7a147d12dcea";        

        return json(['code'=>1,'appid'=>$appid,'secret'=>$secret]);

    }

    public function init_city($fid=0){

        // 读取json文件数据
        $data = file_get_contents('static/city2.json');
        //$data = mb_convert_encoding($data, "UTF-8"); // 如果是编码问题,可以这样转为utf8 

        $data = json_decode(htmlspecialchars_decode($data),true);

        // 解析json字符串
        //echo $errorinfo = json_last_error();//输出4 语法错误

        foreach($data as $prov){
            $arr=['name'=>$prov['name'],'fid'=>0];
            $fid=Db::table('city')->insertGetId($arr);

            foreach($prov['cityList'] as $city){
                $arr2 =['name'=>$city['name'],'fid'=>$fid];
                $fid2 =Db::table('city')->insertGetId($arr2);

                $arr3=[];
                foreach($city['countyList'] as $county){
                    $arr3[] =['name'=>$county['name'],'fid'=>$fid2];
                }
                Db::table('city')->insertAll($arr3);

            }
            echo $prov['name'].",";
        }
        echo "<br/>Complete!";

    // 打印数据
    //return(var_dump($data));

    }

    //城市列表
    public function city_list($fid=0,$tree=0){
        $all = Request::param();

        if($fid || !empty($all['fid'])) $fid = $all['fid'];

        $list = Db::table('city')->where('fid',$fid)->select()->toArray();
        if($tree || !empty($all['tree'])){
            foreach($list as &$row){
                $row['children'] = Db::table('city')->where('fid',$row['id'])->select()->toArray();
            }
        }

        //var_dump($list);
        return json($list);
    }


    //导入csv文件
    public function import_csv(){
        $uid=Session::get('logonid');

        if(empty($uid)) return "请登录!";
        $me=Db::table('user')->where('id',$uid)->find();

        $file='';
        if(!empty($_FILES['csv']) && $_FILES['csv']['size']>0){
            $file = Common::upload($_FILES['csv']);
        }else{
            return View::fetch('customer_import');
        }

        if(!$file['code']) {
            echo "上传失败.";
            return;
        }
        echo "文件已上传《".$file['msg']."》，处理结果如下：</br/><hr/>";

        //$file1= substr($file['msg'],1,strlen($file['msg'])-1);

        $fp = fopen($file['msg'], "r"); 
        //$fp = fopen("upload/excel/test.csv", "r");

        $i = 0;
        $list=[];
        $cnt=0;
        $succ=0;
        $fail=0;

        while ($data = fgetcsv($fp)) {
            $i++;
            /* 第一行抬头不算*/
            if($i == 1) continue;
            //进行转码
            $cnt++;
            $ct=date("Y-m-d H:i:s");

            $row = array(
                'name'=>iconv('GBK','UTF-8',$data[0]),
                'sex'=>iconv('GBK','UTF-8',$data[1])=='男'?1:2,
                'id_card'=>iconv('GBK','UTF-8',$data[2]),
                'mobile'=>iconv('GBK','UTF-8',$data[3]),
                'area'=>iconv('GBK','UTF-8',$data[4]),
                'creater'  => $uid,
                'level'=> 1,
                'password' => substr(md5("12345think"),0,32),
                'create_time'  => $ct,
                'status'=>1,
                'money'=>0,
                'money_v'=>md5($ct.'0'),
                'fee_id'=>'',
                'dept_id'=>$me['dept_id']
            );

            $exist_row = Db::table('customer')->where('mobile',$row['mobile'])->find();
            if($exist_row){
                echo '手机号码重复,'.$row['mobile'].",".$row['name'].'<br />';
                $fail++;
                continue;
            }
            $exist_row = Db::table('customer')->where('id_card',$row['id_card'])->find();
            if($exist_row){
                echo '证件号码重复,'.$row['mobile'].",".$row['name'].'<br />';
                $fail++;
                continue;
            }

            Db::table('customer')->insert($row);
            $succ++;
        };

        echo "<hr/>文档资料数:".$cnt."，导入成功:".$succ."，失败:".$fail;
        fclose($fp);


    }


    //腾讯地图地名查找
    public function address_search(){
        $all=Request::param();
        $remote_url=$all['remote_url'];
        
        $key=iconv('GBK','UTF-8//IGNORE',urlencode($all['key']));
        $add=$all['address'];

        $url=$remote_url."?address=".$add."&key=".$key;

        $data=Common::curl_post('https://apis.map.qq.com/ws/geocoder/v1/',json_encode(['key'=>$key,'address'=>$add]));

        return $data;

    }

    public function commision_set(){
        $all=Request::param();
        $uid=Session::get('logonid');
        if(empty($uid)) return header("location:/index/login");

        if(empty($all['commision']) || !is_numeric($all['commision'])){
            return json(['code'=>0,'msg'=>'commision error!']);
        }

        $res =Db::table('sys')->update(['id'=>1,'commision'=>$all['commision']]);
        return json(['code'=>$res,'msg'=>'修改完成！']);
    }


    function getip(){
        $ip=FALSE;
        //客户端IP 或 NONE 
        if(!empty($_SERVER["HTTP_CLIENT_IP"])){
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }
        //多重代理服务器下的客户端真实IP地址（可能伪造）,如果没有使用代理，此字段为空
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
            if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
            for ($i = 0; $i < count($ips); $i++) {
                if (!eregi ("^(10│172.16│192.168).", $ips[$i])) {
                    $ip = $ips[$i];
                    break;
                }
            }
        }
        //客户端IP 或 (最后一个)代理服务器 IP 
        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
    }
  

    //删除一张图片，并跟新数据库
    //参数：tb:表名，row_id:记录id,field:字段名,src:图片文件名
    function img_remove(){
        $uid=Session::get('logonid');
        if(empty($uid)) return header("location:/index/login");
        $all=Request::param();

        if(empty($all['tb']) || empty($all['row_id']) ||empty($all['field']) ||empty($all['src'])){
            return json(['code'=>0,'msg'=>'参数缺少']);
        }

        //找出记录
        $row=Db::table($all['tb'])->find($all['row_id']); 

        $arr=explode(',',$row[$all['field']]);
        $arr2=[];
        foreach($arr as $img){
            if($img!=$all['src'] && $img!=''){
                $arr2[]=$img;
            }
        }

        $new_image = implode(',',$arr2);
        $res = Db::table($all['tb'])->update(['id'=>$all['row_id'],$all['field']=>$new_image]);

        if($res){
            $res1=Common::rm_file($all['src']);
            return json(['code'=>$res+$res1,'msg'=>'删除成功!'.$all['src']]);
        }else{
            return json(['code'=>0,'msg'=>'删除不成功!']);
        }

    }


    //添加一张图片，并跟新数据库
    //参数：tb:表名+字段名,source_url:来源地，供返回用。
    function img_add(){
        $all=Request::param();
        
        if(empty($all['tb']) || empty($all['source_url'])) return 'Error'.$this->back;
        $tb=explode("+",$all['tb']);
        $tb_name=$tb[0];
        $field=$tb[1];

        //real_key:目标表，真正的key字段
        if(!empty($all['real_key'])) {
            $val=$all['real_key'];
        }else{
            $val=$all['id'];
        }
        $file_index='file1';
        foreach($_FILES as $k=>$v){
            if($v['size']>0){
                $file_index=$k;
                break;
            }
        }
        //halt($all,$_FILES[$file_index],$field,$tb_name);

        if($_FILES[$file_index]['size']>0){
            $files =Common::upload($_FILES[$file_index]);

            if($files['code']){
                $row=Db::table($tb_name)->where('id',$val)->find();

                if(!is_null($row[$field]) && trim($row[$field])!=''){
                    $arr=explode(',',$row[$field]);
                }else{
                    $arr=[];
                }

                $arr[]=$files['msg'];
                
                $res=Db::table($tb_name)->update(['id'=>$val,$field=>implode(',',$arr)]);
                return header("location:".$all['source_url']);
            }else{
                return json(['code'=>0,'msg'=>$files['msg']]);
            }
        }

        return json(['code'=>0,'msg'=>'No file found!']);

        //halt($all,$arr,$_FILES['file1']);
    }

}